from sqlalchemy import or_
from sqlalchemy.orm import Session
from typing import List, Optional, Dict, Any
import logging

from src.models.question import Question
from src.schemas.question import QuestionCreate, QuestionUpdate, QuestionType

# 配置日志（Python 3.12的logging增强）
logger = logging.getLogger(__name__)


def create_question(db: Session, question: QuestionCreate, created_by: str = "AI") -> Question:
    """
    创建新题目

    Args:
        db: 数据库会话
        question: 包含题目信息的Pydantic模型
        created_by: 创建人（默认'AI'，手动创建时为用户名）

    Returns:
        新创建的题目数据库记录
    """
    try:
        # 将Pydantic模型转换为字典，使用Pydantic v2的model_dump方法
        db_question = Question(**question.model_dump(), created_by=created_by)
        db.add(db_question)
        db.commit()
        db.refresh(db_question)
        logger.info(f"Created question with id: {db_question.id}")
        return db_question
    except Exception as e:
        db.rollback()
        logger.error(f"Error creating question: {str(e)}", exc_info=True)
        raise


def batch_create_questions(db: Session, questions: List[QuestionCreate], created_by: str = "AI") -> List[Question]:
    """
    批量创建题目（用于AI生成多道题场景）

    Args:
        db: 数据库会话
        questions: 题目列表
        created_by: 创建人

    Returns:
        创建的题目列表
    """
    try:
        db_questions = [
            Question(**q.model_dump(), created_by=created_by)
            for q in questions
        ]
        db.add_all(db_questions)
        db.commit()
        for q in db_questions:
            db.refresh(q)
        logger.info(f"Batch created {len(db_questions)} questions")
        return db_questions
    except Exception as e:
        db.rollback()
        logger.error(f"Error batch creating questions: {str(e)}", exc_info=True)
        raise


def get_question(db: Session, question_id: int) -> Optional[Question]:
    """根据ID查询单个题目"""
    return db.query(Question).filter(Question.id == question_id).first()


def get_questions(
        db: Session,
        skip: int = 0,
        limit: int = 100,
        question_type: Optional[QuestionType] = None,
        course: Optional[str] = None,
        difficulty_min: Optional[float] = None,
        difficulty_max: Optional[float] = None,
        search_keyword: Optional[str] = None
) -> list[type[Question]]:
    """多条件查询题目列表（支持分页）"""
    query = db.query(Question)

    # 使用Python 3.12的match语句优化条件判断
    if question_type:
        query = query.filter(Question.question_type == question_type)
    if course:
        query = query.filter(Question.course == course)
    if difficulty_min is not None:
        query = query.filter(Question.difficulty >= difficulty_min)
    if difficulty_max is not None:
        query = query.filter(Question.difficulty <= difficulty_max)
    if search_keyword:
        query = query.filter(
            or_(
                Question.content.ilike(f"%{search_keyword}%")
            )
        )

    return query.offset(skip).limit(limit).all()

# 更新学生信息
def update_question(
        db: Session,
        question_id: int,
        question_update: QuestionUpdate
) -> Optional[Question]:
    """更新题目信息"""
    try:
        db_question = get_question(db, question_id)
        if not db_question:
            return None

        # 使用model_dump获取更新数据（排除None值）
        update_data = question_update.model_dump(exclude_unset=True)
        for field, value in update_data.items():
            setattr(db_question, field, value)

        db.commit()
        db.refresh(db_question)
        logger.info(f"Updated question with id: {question_id}")
        return db_question
    except Exception as e:
        db.rollback()
        logger.error(f"Error updating question {question_id}: {str(e)}", exc_info=True)
        raise


def delete_question(db: Session, question_id: int) -> bool:
    """删除题目"""
    try:
        db_question = get_question(db, question_id)
        if not db_question:
            return False

        db.delete(db_question)
        db.commit()
        logger.info(f"Deleted question with id: {question_id}")
        return True
    except Exception as e:
        db.rollback()
        logger.error(f"Error deleting question {question_id}: {str(e)}", exc_info=True)
        raise


# def get_random_questions(
#         db: Session,
#         count: int, **filters
# ) -> List[Question]:
#     """随机抽取指定数量的题目（用于组卷）"""
#     query = db.query(Question)
#
#     # 应用筛选条件
#     for key, value in filters.items():
#         if hasattr(Question, key) and value is not None:
#             query = query.filter(getattr(Question, key) == value)
#
#     # 随机排序并限制数量（不同数据库随机函数不同，这里使用通用写法）
#     return query.order_by("random()").limit(count).all()
